package com.gr.staffpm.projects.model;

import org.apache.wicket.model.LoadableDetachableModel;

import com.gr.staffpm.datatypes.Project;
import com.gr.staffpm.projects.service.ProjectService;


public class DetachableProjectModel extends LoadableDetachableModel<Project> {

    private final long id;
    private final ProjectService projectService;
    private static final long serialVersionUID = 1L;

    public DetachableProjectModel(ProjectService projectService, Project p) {
        this(projectService, Long.valueOf(p.getProjectId()));
    }

    public DetachableProjectModel(ProjectService projectService, long id) {
        this.projectService = projectService;
        if (id == 0) {
            throw new IllegalArgumentException();
        }
        this.id = id;
    }

    @Override
    public int hashCode() {
        return Long.valueOf(id).hashCode();
    }

    /**
     * Used for dataview with ReuseIfModelsEqualStrategy item reuse strategy
     * 
     * @see org.apache.wicket.markup.repeater.ReuseIfModelsEqualStrategy
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(final Object obj) {
        if (obj == this) {
            return true;
        } else if (obj == null) {
            return false;
        } else if (obj instanceof DetachableProjectModel) {
            DetachableProjectModel other = (DetachableProjectModel) obj;
            return other.id == id;
        }
        return false;
    }


    @Override
    protected Project load() {
        // loads project from the database
        return projectService.getProject((int) id);
    }

}
